/*
 * Copyright 2009, Qys Creations 
 * 
 *  This file is part of Chameleon DB.
 *
 *  Chameleon DB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Chameleon DB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Chameleon DB.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */



import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.nio.channels.*;

public class db_file {
	private FileChannel oChannel = null;
	private long lPosition = 0;
	
	db_file(FileChannel oFileChannel) {
		oChannel = oFileChannel;
	}

	public void seek(long lPositionVal) throws Exception{
		lPosition = lPositionVal;
		//System.out.println(Thread.currentThread().getId() + " have seeked to " + lPosition);
	}

	public long readLong() throws Exception{
		synchronized (oChannel) {
			ByteBuffer oData = ByteBuffer.allocate(8);
			LongBuffer oLong = oData.asLongBuffer();
			oData.clear();
			oChannel.position(lPosition);
			oChannel.read(oData);
			lPosition += 8;
			return oLong.get(0);
		}

	}

	public void writeLong(long v) throws Exception{

		synchronized (oChannel) {
			db_bytes oBytes = new db_bytes(8);
			oBytes.write(v);

			ByteBuffer oData = ByteBuffer.allocate(8);

			oData.put(oBytes.getBytes());
			oData.clear();
			oChannel.position(lPosition);
			oChannel.write(oData);
			oChannel.force(false);
			
		}

		lPosition += 8;
	}

	public void write(byte[] bBytes) throws Exception {
		//System.out.println(Thread.currentThread().getId() + " is about to commit a page at position: " + oChannel.position());

		synchronized (oChannel) {
			ByteBuffer oData = ByteBuffer.allocate(bBytes.length);
			oData.put(bBytes);
			oData.clear();
			oChannel.position(lPosition);
			oChannel.write(oData);
			oChannel.force(false);
		}
		lPosition += bBytes.length;
		//System.out.println(Thread.currentThread().getId() + " committed new page " + oChannel.size());
	}
	public long length() throws Exception{
		return oChannel.size();
	}


}
